package com.sky.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.dto.SeckillVoucherDTO;
import com.sky.entity.SeckillVoucher;
import com.sky.exception.RedisException;
import com.sky.mapper.VoucherMapper;
import com.sky.result.PageResult;
import com.sky.service.VoucherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

import static com.sky.constant.RedisConstant.SECKILL_STOCK_KEY;

/**
 * @Author: invictusQAQ
 * @Date: 2023-09-06-16:16
 * @Description:
 */
@Service
public class VoucherServiceImpl implements VoucherService {

    @Autowired
    private VoucherMapper voucherMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 新增秒杀券
     * @param seckillVoucher
     * @return void
     **/
    @Transactional
    public void addSeckillVoucher(SeckillVoucher seckillVoucher) {
        //获取雪花算法全局单例对象
        Snowflake snowflake=IdUtil.getSnowflake(1,1);
        Long seckillVoucherId= snowflake.nextId();
        seckillVoucher.setId(seckillVoucherId);
        voucherMapper.addSeckillVoucher(seckillVoucher);
        //存入库存至Redis为秒杀准备
        stringRedisTemplate.opsForValue().set(SECKILL_STOCK_KEY + seckillVoucher.getId(), seckillVoucher.getStock().toString());
        String result= stringRedisTemplate.opsForValue().get(SECKILL_STOCK_KEY + seckillVoucher.getId());
        if(result==null||"".equals(result)){
            throw new RedisException("代金券插入Redis失败，已回滚");
        }
    }

    /**
     * 秒杀券分页查询
     * @param seckillVoucherDTO
     * @return com.sky.result.PageResult
     **/
    public PageResult pageQuery(SeckillVoucherDTO seckillVoucherDTO) {
        PageHelper.startPage(seckillVoucherDTO.getPage(),seckillVoucherDTO.getPageSize());
        Page<SeckillVoucher> page=voucherMapper.pageQuery(seckillVoucherDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }
}
